<template>
  <div class="carousel-container" ref="carouselRef">
    <!-- 轮播图主体 -->
    <div
        class="carousel-wrapper"
        @mouseenter="pauseAutoPlay"
        @mouseleave="resumeAutoPlay"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >
      <div
          class="carousel-track"
          :style="{
          transform: `translateX(-${currentIndex * 100}%)`,
          transition: isTransitioning ? 'transform 0.5s ease-in-out' : 'none'
        }"
      >
        <div
            v-for="(image, index) in images"
            :key="index"
            class="carousel-slide"
        >
          <img
              :src="image"
              :alt="`轮播图 ${index + 1}`"
              class="carousel-image"
              @load="handleImageLoad"
              @error="handleImageError"
          />
          <!-- 图片描述 -->
<!--          <div v-if="image.caption" class="carousel-caption">-->
<!--            <h3 v-if="image.title" class="caption-title">{{ image.title }}</h3>-->
<!--            <p class="caption-text">{{ image.caption }}</p>-->
<!--          </div>-->
        </div>
      </div>

      <!-- 左右箭头 -->
      <button
          v-if="showArrows && images.length > 1"
          class="carousel-arrow carousel-arrow-left"
          @click="prevSlide"
          :disabled="!infinite && currentIndex === 0"
      >
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>

      <button
          v-if="showArrows && images.length > 1"
          class="carousel-arrow carousel-arrow-right"
          @click="nextSlide"
          :disabled="!infinite && currentIndex === images.length - 1"
      >
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
    </div>

    <!-- 指示器 -->
    <div v-if="showIndicators && images.length > 1" class="carousel-indicators">
      <button
          v-for="(_, index) in images"
          :key="index"
          class="carousel-indicator"
          :class="{ active: index === currentIndex }"
          @click="goToSlide(index)"
          :aria-label="`跳转到第 ${index + 1} 张图片`"
      >
      </button>
    </div>

    <!-- 缩略图 -->
    <div v-if="showThumbnails && images.length > 1" class="carousel-thumbnails">
      <div
          v-for="(image, index) in images"
          :key="index"
          class="thumbnail-item"
          :class="{ active: index === currentIndex }"
          @click="goToSlide(index)"
      >
        <img :src="image.thumbnail || image.url" :alt="image.alt" class="thumbnail-image" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'

// Props定义
const props = defineProps({
  // 图片数组
  images: {
    type: Array,
    required: true,
    default: () => []
  },
  // 自动播放
  autoPlay: {
    type: Boolean,
    default: true
  },
  // 自动播放间隔（毫秒）
  interval: {
    type: Number,
    default: 3000
  },
  // 是否显示箭头
  showArrows: {
    type: Boolean,
    default: true
  },
  // 是否显示指示器
  showIndicators: {
    type: Boolean,
    default: true
  },
  // 是否显示缩略图
  showThumbnails: {
    type: Boolean,
    default: false
  },
  // 是否无限循环
  infinite: {
    type: Boolean,
    default: true
  },
  // 轮播器高度
  height: {
    type: String,
    default: '400px'
  },
  // 初始索引
  initialIndex: {
    type: Number,
    default: 0
  }
})

// Emits定义
const emit = defineEmits(['change', 'click'])

// 响应式数据
const currentIndex = ref(props.initialIndex)
const isTransitioning = ref(true)
const autoPlayTimer = ref(null)
const isAutoPlayPaused = ref(false)
const carouselRef = ref(null)

// 触摸相关
const touchState = reactive({
  startX: 0,
  startY: 0,
  deltaX: 0,
  deltaY: 0,
  isSwiping: false
})

// 计算属性
const totalSlides = computed(() => props.images.length)

// 方法
const nextSlide = () => {
  if (totalSlides.value <= 1) return

  if (props.infinite) {
    currentIndex.value = (currentIndex.value + 1) % totalSlides.value
  } else {
    if (currentIndex.value < totalSlides.value - 1) {
      currentIndex.value++
    }
  }
}

const prevSlide = () => {
  if (totalSlides.value <= 1) return

  if (props.infinite) {
    currentIndex.value = currentIndex.value === 0 ? totalSlides.value - 1 : currentIndex.value - 1
  } else {
    if (currentIndex.value > 0) {
      currentIndex.value--
    }
  }
}

const goToSlide = (index) => {
  if (index >= 0 && index < totalSlides.value) {
    currentIndex.value = index
  }
}

// 自动播放控制
const startAutoPlay = () => {
  if (!props.autoPlay || totalSlides.value <= 1) return

  stopAutoPlay()
  autoPlayTimer.value = setInterval(() => {
    if (!isAutoPlayPaused.value) {
      nextSlide()
    }
  }, props.interval)
}

const stopAutoPlay = () => {
  if (autoPlayTimer.value) {
    clearInterval(autoPlayTimer.value)
    autoPlayTimer.value = null
  }
}

const pauseAutoPlay = () => {
  isAutoPlayPaused.value = true
}

const resumeAutoPlay = () => {
  isAutoPlayPaused.value = false
}

// 触摸事件处理
const handleTouchStart = (e) => {
  const touch = e.touches[0]
  touchState.startX = touch.clientX
  touchState.startY = touch.clientY
  touchState.isSwiping = false
  pauseAutoPlay()
}

const handleTouchMove = (e) => {
  if (!touchState.startX) return

  const touch = e.touches[0]
  touchState.deltaX = touch.clientX - touchState.startX
  touchState.deltaY = touch.clientY - touchState.startY

  // 判断是否为水平滑动
  if (Math.abs(touchState.deltaX) > Math.abs(touchState.deltaY)) {
    touchState.isSwiping = true
    e.preventDefault()
  }
}

const handleTouchEnd = () => {
  if (!touchState.isSwiping) {
    resumeAutoPlay()
    return
  }

  const threshold = 50 // 滑动阈值

  if (Math.abs(touchState.deltaX) > threshold) {
    if (touchState.deltaX > 0) {
      prevSlide()
    } else {
      nextSlide()
    }
  }

  // 重置触摸状态
  touchState.startX = 0
  touchState.startY = 0
  touchState.deltaX = 0
  touchState.deltaY = 0
  touchState.isSwiping = false

  resumeAutoPlay()
}

// 图片加载处理
const handleImageLoad = (e) => {
  console.log('图片加载成功:', e.target.src)
}

const handleImageError = (e) => {
  console.error('图片加载失败:', e.target.src)
  // 可以设置默认图片
  // e.target.src = '/path/to/default-image.jpg'
}

// 键盘事件处理
const handleKeydown = (e) => {
  switch (e.key) {
    case 'ArrowLeft':
      prevSlide()
      break
    case 'ArrowRight':
      nextSlide()
      break
    case ' ':
      e.preventDefault()
      if (isAutoPlayPaused.value) {
        resumeAutoPlay()
      } else {
        pauseAutoPlay()
      }
      break
  }
}

// 监听器
watch(currentIndex, (newIndex, oldIndex) => {
  emit('change', {
    currentIndex: newIndex,
    previousIndex: oldIndex,
    currentImage: props.images[newIndex]
  })
})

watch(() => props.autoPlay, (newVal) => {
  if (newVal) {
    startAutoPlay()
  } else {
    stopAutoPlay()
  }
})

watch(() => props.interval, () => {
  if (props.autoPlay) {
    startAutoPlay()
  }
})

// 生命周期
onMounted(() => {
  if (props.autoPlay) {
    startAutoPlay()
  }

  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  stopAutoPlay()
  document.removeEventListener('keydown', handleKeydown)
})

// 暴露方法给父组件
defineExpose({
  nextSlide,
  prevSlide,
  goToSlide,
  startAutoPlay,
  stopAutoPlay,
  pauseAutoPlay,
  resumeAutoPlay,
  currentIndex: computed(() => currentIndex.value)
})
</script>

<style scoped>
.carousel-container {
  position: relative;
  width: 100%;
  height: v-bind(height);
  overflow: hidden;
  left: 0;
  right: 0;
  margin: 0 auto;
}

.carousel-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.carousel-track {
  display: flex;
  width: 100%;
  height: 100%;
  will-change: transform;
}

.carousel-slide {
  position: relative;
  flex: 0 0 100%;
  width: 100%;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: fill;
  display: block;
}

.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 20px;
  text-align: center;
}

.caption-title {
  margin: 0 0 8px 0;
  font-size: 1.2em;
  font-weight: 600;
}

.caption-text {
  margin: 0;
  font-size: 0.9em;
  opacity: 0.9;
}

/* 箭头样式 */
.carousel-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 2;
}

.carousel-arrow:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: translateY(-50%) scale(1.1);
}

.carousel-arrow:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.carousel-arrow:disabled:hover {
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
}

.carousel-arrow-left {
  left: 16px;
}

.carousel-arrow-right {
  right: 16px;
}

/* 指示器样式 */
.carousel-indicators {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 2;
}

.carousel-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
  background: transparent;
  cursor: pointer;
  transition: all 0.3s ease;
}

.carousel-indicator.active {
  background: white;
}

.carousel-indicator:hover {
  transform: scale(1.2);
}

/* 缩略图样式 */
.carousel-thumbnails {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 2;
}

.thumbnail-item {
  width: 60px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.thumbnail-item.active {
  border-color: white;
}

.thumbnail-item:hover {
  transform: scale(1.1);
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .carousel-arrow {
    width: 40px;
    height: 40px;
  }

  .carousel-arrow-left {
    left: 8px;
  }

  .carousel-arrow-right {
    right: 8px;
  }

  .carousel-caption {
    padding: 12px;
  }

  .caption-title {
    font-size: 1em;
  }

  .caption-text {
    font-size: 0.8em;
  }

  .thumbnail-item {
    width: 50px;
    height: 35px;
  }
}
</style>
